package com.cy.sportassistant.controller;

import com.cy.sportassistant.agent.SportAgent;
import com.cy.sportassistant.common.EmbeddedContent;
import com.cy.sportassistant.embedding.EmbeddingService;
import dev.langchain4j.service.Result;
import dev.langchain4j.service.TokenStream;
import dev.langchain4j.service.tool.ToolExecution;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.time.LocalDate;


@Slf4j
@RequestMapping("/sport")
@RestController
public class SupportAgentController {

    @Resource
    private SportAgent sportAgent;
    @Resource
    private EmbeddingService embeddingService;

    @RequestMapping(value = "/chat", produces = "text/stream;charset=UTF-8")
    public Flux<String> stream(@RequestParam String message, @RequestParam String userId,@RequestParam Boolean webSearsh) {

        //message += "\n今天日期：" + LocalDate.now();

        if (webSearsh) {
            message += "最新";  // 最近 是关键词 会触发websearch
        }

        TokenStream stream = sportAgent.stream(userId, message, LocalDate.now().toString(), webSearsh);

        return Flux.create(sink -> {

            stream.onPartialResponse(sink::next)
                    .onToolExecuted((ToolExecution toolExecution) -> {
                        sink.next("正在执行工具: " + toolExecution.request().name() + "\n");
                        sink.next("工具参数: " + toolExecution.request().arguments() + "\n");
                        sink.next("工具执行结果: " + toolExecution.result() + "\n");
                    })
                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });

    }

    @RequestMapping("embedding")
    public String embedding(@RequestBody EmbeddedContent content) throws IOException {
        embeddingService.processDocument(content.getContent());
        return "success";
    }


}
